<!-- 上传图片的操作 -->
<template>
    <el-upload
        class="avatar-uploader"
        action="/file/uploadImage"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
    >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
</template>

<script>
import { mapMutations } from "vuex";
import * as type from "../../store/mutation-types";
export default {
    name: "UploadImg",
    data() {
        return {
            imageUrl: "",
        };
    },
    methods: {
        ...mapMutations({
            setCurUserImg: type.UPDATE_CURUSER_IMG, //辅助函数进行了映射
        }),
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
            console.log(res);
            if (res.code == 200) {
                this.$message.success("修改头像成功！"); //信息的提示
                this.setCurUserImg(res.data); //这个是使用到了辅助函数，
                // this.$store.commit("updateCurUserImg",res.data);        //这个是没有使用到这个辅助函数
            } else {
                this.$message.success("修改头像失败！"); //信息的提示
            }
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === "image/jpeg";
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error("上传头像图片只能是 JPG 格式!");
            }
            if (!isLt2M) {
                this.$message.error("上传头像图片大小不能超过 2MB!");
            }
            return isJPG && isLt2M;
        },
    },
};
</script>

<style lang="less"  scoped>
.el-upload {
    border: 1px dashed #222020;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.el-upload:hover {
    border-color: #111111;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #1e1f20;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
